#include <stdio.h>    // perror()
#include <stdlib.h>   // exit()
#include <unistd.h>   // ftruncate() / close() / fork() / sleep()
#include <fcntl.h>    // pid_t /
#include <sys/mman.h> // shm_open()/shm_unlink()/mmap()/munmap()
#include <wait.h>     // wait()
#include <string.h>   // strcpy()

int main(int argc, char const *argv[])
{
    char *shm_name = "/shm_test";
    int shm_result = shm_open(shm_name,O_CREAT|O_RDWR,0666); // 创建共享内存
    if(shm_result == -1){
        perror("创建共享内存对象失败\n");
    }
    ftruncate(shm_result,100); // 设置共享内存大小

    char * share = (char *)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_result,0); // 映射共享内存
    if(share == MAP_FAILED){
        perror("映射共享内存失败\n");
    }
    close(shm_result); // 关闭共享内存文件描述符

    pid_t pid = fork();
    if(pid==0){
        char * name = "5201314";
        strcpy(share,name); // 写入共享内存
       printf("子进程写入共享内存成功数据为%s\n",name); 
    }else if (pid>0)
    {
        waitpid(pid, NULL,0);
        char buff[100];
        strcpy(buff,share);
        printf("父进程读取共享内存成功数据为%s\n",buff);
        munmap(share,100); // 解除映射
        int delete_shm = shm_unlink(shm_name);
        if(delete_shm == -1){
            perror("删除共享内存失败\n");
        }
    }
    
    return 0;
}
